package com.xiaozhen.sso.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.R;
import com.xiaozhen.common.core.domain.system.SysUser;
import com.xiaozhen.common.core.utils.SecurityUtils;
import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.sso.feign.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/10/9 11:33
 * @description:
 */
@Api(tags = "统一登录接口")
@RestController
@RequestMapping("/sysLogin")
public class SysLoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;


    @ApiOperation("系统登录接口")
    @PostMapping("doLogin")
    public AjaxResult doLogin(String username, String password) {
        R<SysUser> result = sysUserService.selectByUsername(username);
        SysUser sysUser = result.getData();
        System.out.println("sysUser:" + sysUser);
        if (SecurityUtils.matches(password, sysUser.getPassword())) {
            //判断是否登录
            if (!StpUtil.isLogin()) {
                StpUtil.login(sysUser.getUserId());
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("access_token", StpUtil.getTokenValue());
            return AjaxResult.success("登录成功", jsonObject);
        }
        return AjaxResult.error("登录失败");
    }

    @ApiOperation("注销登陆状态")
    @PostMapping("logout")
    public void logout() {
        StpUtil.logout();
    }

    @ApiOperation("校验token的有效性")
    @PostMapping("checkToken")
    public AjaxResult checkToken(String token) {
        System.out.println(StpUtil.isLogin());
        System.out.println(StpUtil.getTokenValue());
        if (StpUtil.isLogin() && StpUtil.getTokenValue().equals(token)) {
            //有效
            return AjaxResult.success(true);
        }
        //无效
        return AjaxResult.error("无效的token");
    }
}
